import React, { useState, useEffect } from 'react';
import {
  Input,
  DatePicker,
  Button,
  Table,
  Pagination,
  Space,
  Form,
  message,
} from 'antd';
import {
  SearchOutlined,
} from '@ant-design/icons';
import axios from 'axios';

// API基础URL
const API_BASE_URL = 'http://localhost:3000';

const { RangePicker } = DatePicker;

// 入库记录数据类型定义
interface InboundRecord {
  key: string;
  id: number;
  sort: string;
  code: number;
  name: string;
  cate: string;
  actualnum: number;
  fieldName: string;
  warehouse: string;
  reservoir: string;
  location: string;
  add: string;
  addtime: string;
  edit: string;
  edittime: string;
  tracking: string;
  plannum: number;
}

const Rkjilu = () => {
  // 状态管理
  const [inboundRecords, setInboundRecords] = useState<InboundRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取入库记录数据
  const fetchInboundRecords = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/inbound`);
      // 确保返回的数据是数组格式
      const data = Array.isArray(response.data) ? response.data : [];
      setInboundRecords(data);
    } catch (error) {
      console.error('获取入库记录失败:', error);
      message.error('获取入库记录失败');
      // 确保在错误情况下也设置为空数组
      setInboundRecords([]);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchInboundRecords();
  }, []);

  // 搜索处理函数
  const handleSearch = () => {
    console.log('执行搜索操作');
    // 这里可以添加实际的搜索逻辑，比如根据表单值过滤表格数据等
  };

  // 重置处理函数
  const handleReset = () => {
    console.log('执行重置操作');
    // 这里可以添加重置表单的逻辑
  };

  // 表格列配置
  const columns = [
    {
      title: '',
      dataIndex: 'check',
      render: () => <Input type="checkbox" />,
    },
    {
      title: '序号',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '入库单号',
      dataIndex: 'tracking',
      key: 'tracking',
    },
    {
      title: '物品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '计划数量',
      dataIndex: 'plannum',
      key: 'plannum',
    },
    {
      title: '实际数量',
      dataIndex: 'actualnum',
      key: 'actualnum',
    },
    {
      title: '单位',
      dataIndex: 'fieldName',
      key: 'fieldName',
    },
    {
      title: '仓库',
      dataIndex: 'warehouse',
      key: 'warehouse',
    },
    {
      title: '库区',
      dataIndex: 'reservoir',
      key: 'reservoir',
      render: (text) => <span style={{ color: 'blue' }}>{text}</span>,
    },
    {
      title: '库位',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '创建人',
      dataIndex: 'add',
      key: 'add',
      render: (text) => <span style={{ color: 'blue' }}>{text}</span>,
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      {/* 搜索区域 */}
      <Form
        // form={searchForm}
        // onFinish={handleInSearch}
        layout="inline"
        style={{
          marginBottom: '20px'
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%'
          }}
        >
          <Space>
            <Form.Item
              name="outboundNumber"
              rules={[{ whitespace: true }]} // 允许空值，但不允许纯空格
            >
              <Input
                placeholder="请输入入库单号"
                prefix={<SearchOutlined />}
                style={{ width: 150 }}
              />
            </Form.Item>

            <Form.Item name="outboundType">
              <Input
                placeholder="物品名称"
                prefix={<SearchOutlined />}
                style={{ width: 150 }}
              />
            </Form.Item>

            <Form.Item name="customerName">
              <Input
                placeholder="请输入客户名称"
                prefix={<SearchOutlined />}
                style={{ width: 150 }}
              />
            </Form.Item>


          </Space>

          <Space>
            <span>入库时间:</span>
            <Form.Item name="outboundTime">
              <RangePicker style={{ marginLeft: '20px' }} />
            </Form.Item>
          </Space>
        </div>
        <div style={{ width: '100%', textAlign: 'end', marginTop: '20px', marginRight: '25px' }}>
          <Space style={{ marginLeft: '20px' }}>
            <Button type="primary" onClick={handleSearch}>搜索</Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </div>
      </Form>

      {/* 表格区域 */}
      <Table
        dataSource={Array.isArray(inboundRecords) ? inboundRecords : []}
        columns={columns}
        pagination={false} // 先关闭表格自带分页，使用下方自定义分页
        scroll={{ x: 'scroll' }} // 横向滚动
        loading={loading}
        rowKey="id"
      />

      {/* 分页区域 */}
      <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Pagination
          current={currentPage}
          total={Array.isArray(inboundRecords) ? inboundRecords.length : 0}
          pageSize={pageSize}
          onChange={(page, size) => {
            setCurrentPage(page);
            setPageSize(size || 10);
          }}
          showSizeChanger
          showQuickJumper
        />
        <Space>
          <span>{pageSize}条/页</span>
          <span>跳至</span>
          <Input 
            type="text" 
            style={{ width: 50, textAlign: 'center' }} 
            onPressEnter={(e) => {
              const page = parseInt((e.target as HTMLInputElement).value);
              const totalPages = Math.ceil((Array.isArray(inboundRecords) ? inboundRecords.length : 0) / pageSize);
              if (page && page > 0 && page <= totalPages) {
                setCurrentPage(page);
              }
            }}
          />
          <span>页</span>
        </Space>
      </div>
    </div>
  );
};

export default Rkjilu;